package com.wangjiyuan.giftshuo.service;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.wangjiyuan.giftshuo.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateService extends IntentService {
    private Context mContext = this;

    public UpdateService() {
        super("UpdateService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        String updateUrl = intent.getStringExtra("update_url");
        NotificationManager manager = (NotificationManager) getSystemService(Context
                .NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
        builder.setSmallIcon(R.mipmap.icon_app)
                .setContentTitle("文件下载中...")
                .setContentText("已下载0%")
                .setAutoCancel(true);
        //根据网络地址获取到文件需要保存的名称
        String fileName = updateUrl.substring(updateUrl.lastIndexOf("/") + 1);
        Log.e("Service","service fileName=="+fileName);
        //生成当前需要保存的文件路径（保存在SD卡私有files目录下的download子目录下）
        String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                + File.separator + fileName;
        Log.e("Service","service filePath=="+filePath);

        //执行网络下载
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            URL url = new URL(updateUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

            if (httpConn.getResponseCode() == 200) {
                bis = new BufferedInputStream(httpConn.getInputStream());
                //获取文件的总长度
                int totalLength = httpConn.getContentLength();
                //定义局部变量，用来存储当前已经下载的文件的长度
                int currentLength = 0;
                byte[] buffer = new byte[1024 * 8];
                int c;

                while ((c = bis.read(buffer)) != -1) {
                    //随着循环，不断累加当前下载的文件长度
                    currentLength += c;
                    //输出流在指定路径下保存文件
                    bos.write(buffer, 0, c);
                    bos.flush();

                    //动态生成进度通知条
                    int progress = (int) ((currentLength / (float) totalLength) * 100);
                    builder.setProgress(100, progress, false)
                            .setContentText("已经下载" + progress + "%");
                    manager.notify(0, builder.build());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception ex) {
            }
            //自动安装
            Intent myIntent = new Intent();
            myIntent.setAction(Intent.ACTION_VIEW);

            //如果下载文件是视频文件，则执行以下代码（关键在第二个参数MIME格式）
            //myIntent.setDataAndType(Uri.fromFile(new File(filePath)), "video/*");

            //如果下载文件是apk文件，则执行以下代码（关键在第二个参数MIME格式）
            myIntent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");


            PendingIntent pIntent = PendingIntent.getActivity(mContext, 1, myIntent, PendingIntent
                    .FLAG_ONE_SHOT);
            builder.setContentTitle("文件下载完毕！")
                    .setSmallIcon(android.R.drawable.stat_sys_download_done)
                    .setContentText("已下载100%")
                    .setContentIntent(pIntent);

            manager.notify(0, builder.build());
        }

    }
}
